<template>
  <div class="page page-works-index p-5">
    <div class="px-4">
      <div class="banner">

      </div>
      <!-- workcon-hd -->
      <div class="workcon-hd p-t-10">
        <div class="label">
          <div class="tabs flex">

            <div class="tab" v-for="(tab, index) in app.workTypeList" @click="tabIndexChange(index)" :key="index"
              :class="[{ active: tabIndex == index }, `tab${index}`]">
              {{ tab.label }}
            </div>
          </div>
        </div>
        <div class="input" v-show="tabIndex == 0">
          <el-input v-model="keyWord" @keyup.enter="reSearch" placeholder="输入作品名称/昵称/作品ID" size="large"
            style="width: 300px;">
            <template #prepend>
              <el-button :icon="ElIconSearch" @click="reSearch" />
            </template>
          </el-input>
          <div class="btn" v-show="false">
            <el-button type="primary" size="large" @click="reSearch">搜索</el-button>
          </div>

          <el-select v-model="orderType" popper-class="popper-workordertype" placeholder="Select" size="large"
            style="width:150px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <!-- workcon-hd -->
      <div class="genpics  flex flex-wrap" ref="genpicsRef">
        <div class="workinfoitem" v-for="(work, index) in workinfos" :key="work.id">
          <PublicCptWorkInfoItem :workInfo="work" :width="workinfoWitdh" :showAuthor="true" :showEditMenu="false"
            :showFavorMenu="true" @downloadImage="downloadImage">
          </PublicCptWorkInfoItem>

        </div>
      </div>
      <div class="more relative flex justify-center m-4" v-if="hasMore" @click="getMore">
        <el-button type="primary">加载更多</el-button>
      </div>
    </div>

  </div>
</template>
<script setup lang="ts">
import { useAppStore } from "~/stores/app";
import PublicCptWorkInfoItem from '~/components/public/CptWorkInfoItem.vue';

let app = useAppStore();
let { downloadByUrl } = app;
let downloadImage = (workInfo: any) => {
  downloadByUrl({ url: workInfo?.fileUrl, id: workInfo?.id, name: workInfo?.name });
}


let keyWord = ref<any>("");
let orderType = ref<any>("favorsCount");
let tabIndex = ref(0);

function tabIndexChange(index: number) {
  tabIndex.value = index;
  resetPagination();
  getPublicWorkinfos();
}

let options = ref<any>([
  { value: "createTime", label: "最新" },
  { value: "favorsCount", label: "最热" },
]);

import { postAIPublicWorkInfoPage } from '../../service/yapi';
let workinfos = ref<any>([])
let workinfoWitdh = ref(238)
let genpicsRef = ref<any>(null)
let setMasonryLayout = async () => {
  await nextTick();
  let cloumnCount = 5
  const genpics = genpicsRef.value;
  const genpicsWidth = genpics.clientWidth;
  // 向下取整
  // 左右边距2px
  const itemWidth = Math.floor((genpicsWidth - (cloumnCount + 1) * 2) / cloumnCount);
  workinfoWitdh.value = itemWidth
  const items = genpics.querySelectorAll('.workinfoitem');

  items.forEach((item: any) => {
    item.style.width = `${itemWidth}px`;
  });

  // 设置瀑布流样式
  let columnHeights = Array(5).fill(0);
  items.forEach((item: any) => {
    const minHeight = Math.min(...columnHeights);
    const columnIndex = columnHeights.indexOf(minHeight);
    item.style.position = 'absolute';
    item.style.top = `${minHeight}px`;
    item.style.left = `${columnIndex * itemWidth + columnIndex * 2}px`;
    columnHeights[columnIndex] += item.clientHeight + columnIndex * 2;
  });

  genpics.style.position = 'relative';
  genpics.style.height = `${Math.max(...columnHeights)}px`;
}
let pagination = ref({
  total: 0,
  page: 1,
  size: 12
});
watch(
  () => orderType.value,
  () => {
    reSearch();
  }
);
function resetPagination() {
  pagination.value = {
    total: 0,
    page: 1,
    size: 10
  };
  workinfos.value = []
}



let getPublicWorkinfos = async () => {
  let params = {
    order: orderType.value,
    keyWord: keyWord.value,
    page: pagination.value.page,
    size: pagination.value.size,
    topic: ''
  }
  if (tabIndex.value > 0) {
    params.topic = app.workTypeList[tabIndex.value].label  
  }
  let res: any = await postAIPublicWorkInfoPage(params);

  if (res.code == 1000) {
    let { list, pagination: paginationRes } = res.data;
    pagination.value = paginationRes
    workinfos.value = [
      ...workinfos.value,
      ...list
    ]

  } else {
    ElMessage.warning(res.message)
  }
  setMasonryLayout()
}

function reSearch() {
  pagination.value = { total: 0, page: 1, size: 8 };
  workinfos.value = [];
  getPublicWorkinfos();
}
onMounted(() => {
  window.scrollTo(0, 0);
  getPublicWorkinfos()
  window.addEventListener('resize', setMasonryLayout);
});
onUnmounted(() => {
  window.removeEventListener('resize', setMasonryLayout);
});

let hasMore = computed(() => {
  return pagination.value.total >= pagination.value.page * pagination.value.size;
});
function getMore() {
  let { total, page, size } = pagination.value;

  if (page * size < total) {
    pagination.value.page = page + 1;
    getPublicWorkinfos();
  } else {
    ElMessage.warning("没有更多啦，快去创作吧");
  }
}
definePageMeta({ auth: false });
</script>
<style lang="scss">
.page-works-index {
  .banner {
    height: 200px;
    background: url('https://cdn.codinghou.cn/coding/pc-ai/icons/AI-banner1.jpg') no-repeat center center;
    background-size: cover;
  }

  .workcon-hd {
    font-size: 26px;
    margin-left: 10px;
    padding-left: 20px;
    box-sizing: border-box;
    margin-bottom: 50px;
    display: flex;
    justify-content: space-between;

    .el-input {
      border: 1px solid var(--purple);
      border-radius: 9px;
      margin-right: 12px;
      background: #323232;

      .el-input__inner {
        // color: #fff;
      }
    }

    .tabs {
      .tab {
        @apply text-xl box-border p-t-2 p-b-2 p-r-4 p-l-4 m-r-2 round-lg cursor-pointer;
        color: #1D255A;

        &.active {
          background: #ccc;
        


          border-radius: 9px;
        }
      }

      .tab0 {
        background: #F2F3F9;

      }
    }

    .input {
      padding-right: 40px;
      display: flex;

      .btn {
        margin: 0 10px;
      }
    }
  }

  .el-select--large .el-select__wrapper {
    padding: 15px 16px;
    background: #F2F3F9;
  }


  .genpics {
    display: flex;

    .cpt-comfy-workinfoitem {
      margin: 1px;
    }
  }

  .genpics>* {}


  // AI-banner1
}
</style>